﻿using System;
using System.Collections.Generic;
using WAD.Model.JSON.Oauth;
using Newtonsoft.Json;
using GlTool.GlHttp;

namespace WAD.BLL
{
    public class OAuthBLL
    {
        int OAuth(string code, string state)
        {
            //第二步：通过 Code 获取Access Token
            string url2 = "https://graph.qq.com/oauth2.0/token?";
            string query = string.Format("grant_type=authorization_code&code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&state={4}", QQLoginConfig.APPID, QQLoginConfig.APPKEY, QQLoginConfig.Redirect_Uri, state);
            string html = GetHtml(url2 + query);

            MQQLogin json = JsonConvert.DeserializeObject<MQQLogin>(html);
            if (json == null || string.IsNullOrEmpty(json.Access_Token))
                return 1;

            //第三步:通过 Access Token 获取OpenID
            string url3 = string.Format("https://graph.qq.com/oauth2.0/me?access_token={0}", json.Access_Token);
            html = GetHtml(url3);
            json = JsonConvert.DeserializeObject<MQQLogin>(html);

            if (json == null || string.IsNullOrEmpty(json.OpenID))
                return 2;

            //第四步： 获取用户头像、昵称
            string url4 = "https://graph.qq.com/user/get_user_info?access_token=YOUR_ACCESS_TOKEN&oauth_consumer_key=YOUR_APP_ID&openid=YOUR_OPENID";
            html = GetHtml(url4);
            json = JsonConvert.DeserializeObject<MQQLogin>(html);

            if (json == null || string.IsNullOrEmpty(json.Ret))
                return 3;

            return 0;
        }


        string GetHtml(String url)
        {
            GlHttpGet httpGet = new GlHttpGet();

            //设置浏览器标识
            httpGet.setHead("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36");
            httpGet.Url = url;

            GlHttpResponse response = httpGet.Execute();
            if (response == null)
            {
                return null;
            }
            return response.ToString();
        }
    }
}
